/**
 * Created by huhai on 17/7/5.
 */
import './map/css/index_detail.scss'
import * as d3 from 'd3'
import * as topojson from 'topojson'
import toporoot from './assets/js/chinaMap'
import gBarChart from "../../public_components/g_bar_chart"
import api from '../../api/member'
const centerPoints = [
  {
    name: '西南',
    point: [103.924003,28.796585]
  },
  {
    name: '西北',
    point: [94.605943,36.752842]
  },
  {
    name: '华中',
    point: [114.116105,28.764814]
  },
  {
    name: '华南',
    point: [110.233035,23.524606]
  },
  {
    name: '华东',
    point: [118.715429,32.246466]
  },
  {
    name: '华北',
    point: [113.614073,40.951504]
  },
  {
    name: '东北',
    point: [126.728072,45.894927]
  }
]
let boot= {
  meregeAllArea: function(area_data_json){
    return topojson.merge(area_data_json, area_data_json.objects.china.geometries.filter(function (d) {
      return true
    }))
  },
  initChinaMap: function(){
    api.deviceMap()
      .then((res) => {
        if (res.data.success) {
          const data = res.data.data
          const offsetWidth = parseInt(d3.select('.deviceMap').style('width'))
          let width = 714
          let height = 664
          let scale = 600
          const svgWidth = parseInt(d3.select('.deviceMap').style('width'))
          d3.select('.device_detail_content')
            .text(data[0].describe)
          width = parseInt(d3.select('.deviceMap').style('width')) * 0.6
          height = parseInt(d3.select('.deviceMap').style('height'))
          if (offsetWidth <= 1200) {
            scale = 570
          } else if (offsetWidth <= 1367) {
            scale = 650
          } else if (offsetWidth <= 1440) {
            scale = 750
          }  else if (offsetWidth <= 1680) {
            scale = 800
          } else if (offsetWidth <= 1920) {
            scale = 1000
          }
          d3.select('svg.map').selectAll('.gContainer').remove()
          let svg = d3.select('svg.map').attr('transform', 'translate(' + 20 + ',' + 0 + ')').append('g').attr('transform', 'translate(' + 30 + ',' + 60 + ')').attr('class', 'gContainer')
          let projection = this.projection = d3.geoMercator()
            .center([107, 31])
            .scale(scale)
            .translate([width / 2, height / 2])
          let path = d3.geoPath()
            .projection(projection)
          // 西南
          var south_east = d3.set([
            "四川","重庆","贵州","西藏","云南"
          ]);
          // 西北
          var north_west = d3.set([
            "陕西","甘肃","宁夏","新疆","青海","河南"
          ]);
          // 华中
          var mainland_center = d3.set([
            "湖北","湖南","福建","江西"
          ])
          // 华南
          var mainland_south = d3.set([
            "广西","广东","海南", "台湾"
          ])
          // 华东
          var mainland_east = d3.set([
            "上海","江苏","浙江","安徽","山东"
          ])
          // 华北
          var mainland_north = d3.set([
            "北京","天津","河北","内蒙古", "山西"
          ])
          // 东北
          var east_north = d3.set([
            "黑龙江","吉林","辽宁"
          ])


          // 将TopoJSON对象转换成GeoJSON，保存在georoot中
          var georoot = topojson.feature(toporoot, toporoot.objects.china)
          var east_north_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return east_north.has(d.properties.name)
          }))
          east_north_polygon.area_name="东北"

          var mainland_north_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return mainland_north.has(d.properties.name)
          }))
          mainland_north_polygon.area_name="华北"

          var mainland_east_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return mainland_east.has(d.properties.name)
          }))
          mainland_east_polygon.area_name="华东"

          var mainland_south_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return mainland_south.has(d.properties.name)
          }))
          mainland_south_polygon.area_name="华南"



          var mainland_center_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return mainland_center.has(d.properties.name)
          }))
          mainland_center_polygon.area_name="华中"


          var north_west_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return north_west.has(d.properties.name)
          }))
          north_west_polygon.area_name="西北"


          var south_east_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
            return south_east.has(d.properties.name)
          }))
          south_east_polygon.area_name="西南"
          //
          //
          // var taiwan_polygon = topojson.merge(toporoot, toporoot.objects.china.geometries.filter(function (d) {
          //   return d.properties.name === '台湾'
          // }))
          // taiwan_polygon.area_name="台湾"


          var china = svg.append('g').attr('class', 'china_map')

          var allAreasPolygon=[
            east_north_polygon,
            mainland_north_polygon,
            mainland_east_polygon,
            mainland_south_polygon,
            mainland_center_polygon,
            north_west_polygon,
            south_east_polygon]

          var maxColor = '#54B4DC';
          // var minColor = '#347190'
          var max = d3.max(data[0].districts, function (d) {
            return d.value
          })
          var newValue = []
          var newAge = []
          var districtsValue = 0
          var linear = d3.scaleLinear()
            .domain([0, max])
            .range([0, 1])
          newAge = data[0].all_china.years_of_use.map((val) => {
            val.list_item_name = val.name
            val.list_item_value = val.value * 100
            return val
          })
          boot.radarChart(data[0].all_china.brand_share, '#brand_spread')
          gBarChart('#age_spread', {
            title: "使用年限分布",
            lists: newAge
          }, true)

          allAreasPolygon.forEach((Polygon) => {
            china.append('path')
              .datum(Polygon)
              .attr('class', 'big_area')
              .attr('data-areaname', Polygon)
              .style('fill', maxColor)  // 用蓝色标注
              .style('fill-opacity', function (d) {
                newValue = data[0].districts.filter(function (val) {
                  return val.name === d.area_name + '区'
                })
                if (!newValue.length) {
                  districtsValue = max
                } else {
                  districtsValue = newValue[0].value
                }
                return linear(districtsValue)
              })
              // .style('filter', 'url(#blue-glow)')
              .attr('stroke', '#82e3ff')
              .attr('stroke-opacity', '1')
              .attr('stroke-width', 0)
              .attr('d', path)
              .on("click", function (area_path_data) {
                d3.select(".selected").attr("class", "big_area")
                d3.select(this).attr("class", "big_area selected")
                d3.select('.spread_title')
                  .text(area_path_data.area_name + '区')
                boot.centerCircle(area_path_data, projection, svg, svgWidth, height)
                newValue = data[0].districts.filter(function (val) {
                  return val.name === area_path_data.area_name + '区'
                })
                newAge = newValue[0].years_of_use.map((val) => {
                  val.list_item_name = val.name
                  val.list_item_value = val.value * 100
                  return val
                })
                boot.radarChart(newValue[0].brand_share, '#brand_spread')
                gBarChart('#age_spread', {
                  title: "使用年限分布",
                  lists: newAge
                }, true)
                d3.selectAll('.lend_dot').node().click()
                var event = d3.event;
                event.stopPropagation();
              }, true)
          })
          d3.select('.deviceMap').on('click', function () {
            d3.select(".selected").attr("class", "big_area")
            svg.selectAll('.polyline').remove()
            svg.select('g.dots').remove()
            svg.select('g.aimDot').remove()
            d3.select('.spread_title')
              .text('全国')
            newAge = data[0].all_china.years_of_use.map((val) => {
              val.list_item_name = val.name
              val.list_item_value = val.value * 100
              return val
            })
            boot.radarChart(data[0].all_china.brand_share, '#brand_spread')
            gBarChart('#age_spread', {
              title: "使用年限分布",
              lists: newAge
            }, true)
            d3.selectAll('.lend_dot').node().click()
          })
          d3.selectAll('.lend_dot').on('click', function (d, i , ele) {
            if (!d3.select(ele[i]).classed('active')) {
              d3.selectAll('.lend_dot').classed('active', false)
              d3.select(ele[i]).classed('active', true)
              d3.selectAll('.slide_content').style('transform', 'translateX(' + i * (-100) + '%)')
            }
            var event = d3.event;
            event.stopPropagation();
          }, true)
        }
      })
  },
  radarChart: function (data, eleClass) {
    d3.select(eleClass).selectAll('svg').remove();
    var svg = d3.select(eleClass)
      .append('svg')
      .attr('width', '100%')
      .attr('height', '100%')
    var svgWidth = document.querySelector(eleClass).offsetWidth,
      svgHeight = document.querySelector(eleClass).offsetHeight;
    var main = svg.append('g')
      .attr('class', 'main')
      .attr('transform', "translate(" + svgWidth/2 + ',' + svgHeight/2 + ')');
    // 设定一些方便计算的常量
    var radius = d3.min([svgHeight, svgWidth]) / 2.3,
      // 指标的个数，即fieldNames的长度
      total = data.length,
      // 需要将网轴分成几级，即网轴上从小到大有多少个正多边形
      level = 4,
      // 网轴的范围，类似坐标轴
      rangeMin = 0,
      rangeMax = d3.max(data, function (d) {
        return d.value
      }),
      arc = 2 * Math.PI;
// 每项指标所在的角度
    var onePiece = arc/total;
// 计算网轴的正多边形的坐标
    var polygons = {
      webs: [],
      webPoints: []
    };

    for(var k=level;k>0;k--) {
      var webs = '',
        webPoints = [];
      var r = radius/level * k;
      for(var i=0;i<total;i++) {
        var x = r * Math.sin(-i * onePiece + 5 * onePiece / 2),
          y = r * Math.cos(-i * onePiece + 5 * onePiece / 2);
        webs += x + ',' + y + ' ';
        webPoints.push({
          x: x,
          y: y
        });
      }
      polygons.webs.push(webs);
      polygons.webPoints.push(webPoints);
    }

    var webG = main.append('g')
      .attr('class', 'webs');
    webG.selectAll('polygon')
      .data(polygons.webs)
      .enter()
      .append('polygon')
      .attr('points', function(d) {
        return d;
      })
      .attr('fill-opacity', 0.35)
      .attr('stroke-width', function (d, i) {
        if (i === 0) {
          return 2.5
        } else {
          return 1
        }
      })
      .attr('stroke', function (d, i) {
        if (i === 0) {
          return '#70DAFD'
        } else {
          return 'rgba(112,218,253, 0.2)'
        }
      })
      .attr('fill', function (d, i) {
        if (i === 0) {
          return '#70DAFD'
        }
        else {
          return 'none'
        }
      });
    var lines = main.append('g')
      .attr('class', 'lines');
    lines.selectAll('line')
      .data(polygons.webPoints[0])
      .enter()
      .append('line')
      .attr('x1', 0)
      .attr('y1', 0)
      .attr('x2', function(d) {
        return d.x;
      })
      .attr('y2', function(d) {
        return d.y;
      });

    var circles = main.append('g')
      .attr('class', 'circles');
    circles.selectAll('circle')
      .data(polygons.webPoints[0])
      .enter()
      .append('circle')
      .attr('cx', function(d) {
        return d.x;
      })
      .attr('cy', function(d) {
        return d.y;
      })
      .attr('r', 5)
      .attr('fill', function(d, index) {
        return '#70DAFD';
      });
    var areasData = [];
    var area = '',
      points = [];
    for(var k=0;k<total;k++) {
      var r = radius * (data[k].value - rangeMin)/(rangeMax - rangeMin);
      var x = r * Math.sin(-k * onePiece + 5 * onePiece / 2),
        y = r * Math.cos(-k * onePiece + 5 * onePiece / 2);
      area += x + ',' + y + ' ';
      points.push({
        x: x,
        y: y
      })
    }
    areasData.push({
      polygon: area,
      points: points
    });

    var areas = main.append('g')
      .classed('areas', true);

// 添加g分组用来包含一个雷达图区域下的多边形以及圆点
    areas.selectAll('g')
      .data(areasData)
      .enter()
      .append('g')
      .attr('class',function(d, i) {
        return 'area' + (i+1);
      });
    for(var i=0;i<areasData.length;i++) {
      // 依次循环每个雷达图区域
      var areaDom = areas.select('.area' + (i+1)),
        areaData = areasData[i];
      // 绘制雷达图区域下的多边形
      areaDom.append('polygon')
        .attr('points', areaData.polygon)
        .attr('stroke', '#70DAFD')
        .attr('stroke-width', 2.5)
        .attr('fill-opacity', 0.5)
        .attr('fill', function(d, index) {
          return '#70DAFD';
        });
    }

    var names = main.append('g')
      .classed('names', true);

    names.selectAll('text')
      .data(polygons.webPoints[0])
      .enter()
      .append('text')
      .attr('fill', '#70DAFD')
      .attr('class', function (d, i) {
        return 'name' + i
      })
      .text(function (d, i) {
        return data[i].name.slice(0, 5)
      })
      .attr('x', function(d, i, ele) {
        var x = 0
        if ((i * onePiece + onePiece / 2) > Math.PI) {
          x = d.x - ele[i].getBBox().width - 15;
        }
        else {
          x = d.x + 15
        }
        return x;
      })
      .attr('y', function(d) {
        return d.y;
      })

    var percents = main.append('g')
      .classed('percents', true);

    percents.selectAll('text')
      .data(polygons.webPoints[0])
      .enter()
      .append('text')
      .text(function (d, i) {
        return parseFloat((data[i].value * 100).toFixed(1)) + '%'
      })
      .attr('fill', '#70DAFD')
      .attr('x', function(d, i, ele) {
        var x = 0
        if ((i * onePiece + onePiece / 2) > Math.PI) {
          var nameWidth = names.selectAll('.name' + i).node().getBBox().width
          var percentWidth = ele[i].getBBox().width
          if (nameWidth > percentWidth) {
            percentWidth = nameWidth
          } else {
            names.selectAll('.name' + i)
              .attr('x', d.x - percentWidth - 15)
          }
          x = d.x - percentWidth - 15;
        }
        else {
          x = d.x + 15
        }
        return x;
      })
      .attr('y', function(d, i, ele) {
        return d.y + ele[i].getBBox().height;
      })
  },
  centerCircle: function (area_path_data, projection, svg, width, height) {
    let centerpoint = []
    let twoLinePoint = []
    let threeLinePoint = []
    let endLinePoint = [-30, -60]
    twoLinePoint[0] = width * 0.55 - 50
    twoLinePoint[1] = height * 0.56 - 75
    threeLinePoint[0] = width * 0.55 + 15 - 50
    threeLinePoint[1] = height * 0.56 + 15 - 75
    endLinePoint[0] = width * 0.65 - 94
    endLinePoint[1] = height * 0.56 + 15 - 75
    if (width >= 1600) {
      endLinePoint[0] -=23
    }
    centerPoints.forEach(function (val) {
      if (val.name === area_path_data.area_name) {
        centerpoint = val.point
      }
    })
    const centerProjection = projection(centerpoint)
    svg.selectAll('.polyline').remove()
    var polyline = svg.append('g').attr('class', 'polyline').append('polyline')
    polyline.attr('points', centerProjection.join(',') + ' ' + twoLinePoint.join(',') + ' ' + threeLinePoint.join(',') + ' ' + endLinePoint.join(','))
    polyline.style('stroke', '#70DAFD')
    polyline.style('stroke-width', '1.3')
    polyline.style('fill', 'none')
    svg.select('g.dots').remove()
    var dotG = svg.append('g').attr('class', 'dots')
    dotG.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 4)
      .attr('fill', '#FFFAFF')

    dotG.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 15)
      .attr('fill', 'url(#grad1)')

    dotG.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 2)
      .attr('fill', '#FFFAFF')

    // aim dot
    svg.select('g.aimDot').remove()
    var aimDot = svg.append('g').attr('class', 'aimDot')
    aimDot.selectAll('.aim').remove()
    // brightingest circle
    // aimDot.append('circle')
    //   .attr('class', 'point')
    //   .attr('cx', centerProjection[0])
    //   .attr('cy', centerProjection[1])
    //   .attr('r', 6)
    //   .style('fill', '#b3eeff')
    //   .style('filter', 'url(#blue-glow)')

    // circle inner

    aimDot.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 10)
      .attr('fill', 'none')
      .attr('stroke', '#fff')
      .attr('stroke-opacity', 0.6)
      .attr('stroke-width', '2')
      .attr('stroke-dasharray', '7,2')
    // middle inner

    aimDot.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 18)
      .attr('fill', 'none')
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)
    // middle inner

    aimDot.append('circle')
      .attr('class', 'point')
      .attr('cx', centerProjection[0])
      .attr('cy', centerProjection[1])
      .attr('r', 26)
      .attr('fill', 'none')
      .attr('stroke', '#fff')
      .attr('stroke-opacity', 0.4)
      .attr('stroke-width', 1)

    // line left
    aimDot.append('line')
      .attr('x1', centerProjection[0] - 10)
      .attr('y1', centerProjection[1])
      .attr('x2', centerProjection[0] - 35)
      .attr('y2', centerProjection[1])
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)

    // line right
    aimDot.append('line')
      .attr('x1', centerProjection[0] + 10)
      .attr('y1', centerProjection[1])
      .attr('x2', centerProjection[0] + 35)
      .attr('y2', centerProjection[1])
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)

    // line up
    aimDot.append('line')
      .attr('x1', centerProjection[0])
      .attr('y1', centerProjection[1] - 10)
      .attr('x2', centerProjection[0])
      .attr('y2', centerProjection[1] - 35)
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)
    // line down
    aimDot.append('line')
      .attr('class', 'down')
      .attr('x1', centerProjection[0])
      .attr('y1', centerProjection[1] + 10)
      .attr('x2', centerProjection[0])
      .attr('y2', centerProjection[1] + 35)
      .attr('stroke', '#fff')
      .attr('stroke-width', 1)
  }

}

boot.initChinaMap()
window.onresize= function () {
  // boot.initChinaMap()
}